package com.mishow.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request.Method;
import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.bean.HotSearchBean;
import com.mishow.bean.MenuItemBean;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.HotSearchResponse;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.CommonUtil;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.widget.AdjustLayout;
import com.mishow.widget.MenuPopWindow;
/**
 * 
 * 作者：wei.miao<br/>
 * 描述：搜索界面
 */
public class SearchActivity extends BaseActivity implements OnClickListener{
	/** 返回 **/
	private Button back_btn;
	/** 取消 **/
	private Button btn_search_right;
	/** 菜单选项 **/
	private MenuPopWindow menuPopWindow = null;
	/** 热门搜索数据 **/
	private List<HotSearchBean> hotdatas = new ArrayList<HotSearchBean>();
	/** 历史搜索数据 **/
	private List<HotSearchBean> historydatas = new ArrayList<HotSearchBean>();
	
	private SharedPreferencesUtil preference; // 历史数据存储
	
	/** 热门搜索AdjustLayout **/
	private AdjustLayout adjust_hot_layout;
	
	/** 历史搜索AdjustLayout **/
	private AdjustLayout adjust_history_layout;
	
	/** 清除历史搜索 **/
	private TextView clear_recent_text;
	
	
	/** 热门搜索TextView**/
	private TextView hot_search_text;
	/** 热门搜素linear **/
	private LinearLayout hot_search_linear;
	
	
	/** 控制键盘 **/
	private InputMethodManager imm;
	
	private ImageView image_search;
	/** 搜索输入框 **/
	private EditText et_keyword;
	
	/** 清除历史记录 **/
	private LinearLayout clear_linear;
	/** 历史记录TextView **/
	private TextView recent_search_text;
	/**
	 * 跳转进入搜索界面
	 * 
	 * @param context
	 *            上下文环境
	 * @param keyword
	 *            搜索关键字
	 * @param from
	 *            标识从某个页面进入该搜索页面
	 */
	public static void intoActivity(Context context, String keyword, int from) {
		Intent intent = new Intent(context, SearchActivity.class);
		intent.putExtra("keyword", keyword);
		intent.putExtra("fromPage", from);
		context.startActivity(intent);
	}

	@Override
	protected void initData() {
		
		preference = new SharedPreferencesUtil(this);
		
		for (int i = 0; i < 4; i++) {
			
			HotSearchBean hot = new HotSearchBean();
			hot.setGhwName("主持主播");
			
			hotdatas.add(hot);
		}
		
		for (int i = 0; i < 4; i++) {
			
			HotSearchBean history = new HotSearchBean();
			history.setGhwName("摄影摄像");
			
			historydatas.add(history);
		}
		
	}

	@Override
	protected void initView(Bundle savedInstanceState) {
	
		setContentView(R.layout.activity_search);
		back_btn = (Button) findViewById(R.id.back_btn);
		btn_search_right = (Button)findViewById(R.id.btn_search_right);
		
		image_search = (ImageView)findViewById(R.id.image_search);
		et_keyword = (EditText)findViewById(R.id.et_keyword);
		
		adjust_hot_layout = (AdjustLayout)findViewById(R.id.adjust_hot_layout);
		adjust_history_layout = (AdjustLayout)findViewById(R.id.adjust_history_layout);
		
		hot_search_text = (TextView)findViewById(R.id.hot_search_text);
		hot_search_linear = (LinearLayout)findViewById(R.id.hot_search_linear);
		
		clear_recent_text = (TextView)findViewById(R.id.clear_recent_text);
		
		recent_search_text = (TextView)findViewById(R.id.recent_search_text);
		
		clear_linear = (LinearLayout)findViewById(R.id.clear_linear);
		
		initMenuPop();
	}

	@Override
	protected void setAttribute() {
		
		back_btn.setOnClickListener(this);
		btn_search_right.setOnClickListener(this);
		image_search.setOnClickListener(this);
		clear_recent_text.setOnClickListener(this);
		
		back_btn.setText("通知");
		btn_search_right.setVisibility(View.VISIBLE);
		btn_search_right.setText("搜索");
		
		dogetData();//获取传递keyword
		getRecentDatas(); // 获取本地历史搜索记录
		
		filledHotDatas();
		filledHistoryDatas();
		//getHotSearchData(); // 获取热词搜索
	}

	/**
	 * 获取传递keyword
	 */
	private void dogetData() {
		Intent intent = getIntent();
		if (intent != null) {
			String keyword = intent.getStringExtra("keyword");
			if (!TextUtils.isEmpty(keyword)) {
				et_keyword.setText(keyword);
				et_keyword.setSelection(et_keyword.getText().length()); // 设置光标位置
			}
		}
	}
	
	/**
	 * 获取本地搜索历史记录
	 */
	private void getRecentDatas() {
		String jsonStr = preference.getLastSearch(SharedPreferencesUtil.HOSTORY_SEARCH);
		if (!TextUtils.isEmpty(jsonStr)) {
			historydatas.clear();
			try {
				historydatas.addAll(JSON.parseArray(jsonStr, HotSearchBean.class));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//isClearShow();
	}
	
	
	/**
	 * 服务端获取热词搜索
	 */
	private void getHotSearchData() {
		// 判断网络是否连接
		if (!AndroidUtil.isNetworkAvailable(this)) {
			Toast.makeText(this,"无网络", Toast.LENGTH_SHORT).show();
			return;
		}
		showProgress(null, null, true);
		Map<String, String> params = new HashMap<String, String>();
		
		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(this, params);
		String url = HttpUrlConstant.getPostUrl(this, HttpUrlConstant.HOT_WORDS);
		OnResponseListener<HotSearchResponse> listener = new OnResponseListener<HotSearchResponse>(this) {

			@Override
			public void onSuccess(HotSearchResponse response) {
				getHotWordShow(response);
			}

			@Override
			public void onError(String code, String message) {
				dismissProgress();
				CommonUtil.makeText(SearchActivity.this, message);
			}

			@Override
			public void onCompleted() {
				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<HotSearchResponse>(Method.POST, url, HotSearchResponse.class, listener,
				listener).setParams(lastParams));
	}
	
	
	/**
	 * 清楚历史记录按钮显示
	 */
	private void isClearShow() {
		if (historydatas == null || historydatas.size() == 0) {
			adjust_history_layout.setVisibility(View.GONE);
			clear_linear.setVisibility(View.GONE);
			recent_search_text.setVisibility(View.GONE);
		} else {
			adjust_history_layout.setVisibility(View.VISIBLE);
			clear_linear.setVisibility(View.VISIBLE);
			recent_search_text.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_btn:
			menuPopWindow.showPopWin(back_btn);//分类
			break;
		case R.id.btn_search_right: //取消
			//finish();
			SearchResultActivity.intoActivity(SearchActivity.this);
			break;
		case R.id.image_search: //搜索
			//SearchResultActivity.intoActivity(SearchActivity.this);
			break;
		default:
			break;
		}
	}
	
	
	/**
	 * 初始化菜单栏
	 */
	private void initMenuPop() {
		ArrayList<MenuItemBean> menuContents = new ArrayList<MenuItemBean>();
		menuContents.add(new MenuItemBean("通告"));
		menuContents.add(new MenuItemBean("红人"));
		menuContents.add(new MenuItemBean("机构"));
		menuContents.add(new MenuItemBean("专题"));
		menuPopWindow = new MenuPopWindow(this, menuContents);
		menuPopWindow.setItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				switch (position) {
				case 0:
					back_btn.setText("通告");
					break;
				case 1:
					back_btn.setText("红人");
					break;
				case 2:
					back_btn.setText("机构");
					break;
				case 3:
					back_btn.setText("专题");
					break;
				default:
					break;
				}
				menuPopWindow.closePopWin();
			}
		});
	}
	
	
	
	
	/**
	 * 获取热词显示
	 */
	private void getHotWordShow(HotSearchResponse bean) {
		List<HotSearchBean> obj = null;
		if (obj != null) {
			hotdatas.clear();
			hotdatas.addAll(obj);
		}
		filledHotDatas();
		emptyHotShow();
	}
	
	/**
	 * 热门搜索为空时隐藏
	 */
	private void emptyHotShow() {
		if (hotdatas == null || hotdatas.size() == 0) {
			hot_search_text.setVisibility(View.GONE);
			hot_search_linear.setVisibility(View.GONE);
		} else {
			hot_search_text.setVisibility(View.VISIBLE);
			hot_search_linear.setVisibility(View.VISIBLE);
		}
	}
	
	/**
	 * 填充显示热门搜索
	 */
	private void filledHotDatas() {
		
		for (final HotSearchBean bean : hotdatas) {
			View view = LayoutInflater.from(this).inflate(R.layout.item_hot_search, null);
			TextView textView = (TextView) view.findViewById(R.id.hot_search_text);
			textView.setText(bean.getGhwName());
			textView.setSingleLine(true);
			textView.setEllipsize(TruncateAt.MIDDLE);
			adjust_hot_layout.addView(view);
			textView.setOnClickListener(new View.OnClickListener() { // 点击热门搜索跳转
				@Override
				public void onClick(View v) {
					colseinputMethod(); // 先关闭软键盘
					saveRecentDatas(bean); // 保存点击的搜索热词
				}
			});
		}
		
	}
	
	/**
	 * 填充显示历史搜索
	 */
	private void filledHistoryDatas() {
		
		for (final HotSearchBean bean : historydatas) {
			View view = LayoutInflater.from(this).inflate(R.layout.item_hot_search, null);
			CheckBox textView = (CheckBox) view.findViewById(R.id.hot_search_text);
			textView.setText(bean.getGhwName());
			textView.setSingleLine(true);
			textView.setEllipsize(TruncateAt.MIDDLE);
			adjust_history_layout.addView(view);
			textView.setOnClickListener(new View.OnClickListener() { // 点击热门搜索跳转
				@Override
				public void onClick(View v) {
					colseinputMethod(); // 先关闭软键盘
					saveRecentDatas(bean); // 保存点击的搜索热词
				}
			});
		}
		
	}
	/**
	 * 关闭键盘
	 */
	private void colseinputMethod() {
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et_keyword.getWindowToken(), 0);
	}
	
	
	/**
	 * 保存最近搜索内容
	 */
	private void saveRecentDatas(HotSearchBean wordbean) {

		LinkedList<HotSearchBean> temp = new LinkedList<HotSearchBean>(historydatas);
		for (Iterator<HotSearchBean> iterator = temp.iterator(); iterator.hasNext();) {
			// 本地已有该关键字则去除该关键字
			if (wordbean.getGhwName() == null) {
				return;
			}
			if (wordbean.getGhwName().equals(iterator.next().getGhwName())) {
				iterator.remove();
			}
		}
		temp.addFirst(wordbean);
		// 目前本地最多保存10个搜索关键字
		if (temp.size() > 10) {
			
			temp.removeLast();
		}
		String jsonStr = JSON.toJSONString(temp);
		preference.saveLastSearch(jsonStr, SharedPreferencesUtil.HOSTORY_SEARCH);

	}
}
